package com.example.email;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;

import java.io.IOException;

@WebServlet("/sendEmail")
public class SendEmailServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String email = request.getParameter("email");

        if (email == null || email.isEmpty()) {
            response.getWriter().write("{\"success\":false,\"message\":\"邮箱不能为空\"}");
            return;
        }

        // 生成6位验证码
        String code = generateVerificationCode();

        // 发送邮件
        boolean success = sendVerificationEmail(email, code);

        if (success) {
            // 将验证码保存到 session 中，用于后续验证
            request.getSession().setAttribute("email_code", code);
            response.getWriter().write("{\"success\":true}");
        } else {
            response.getWriter().write("{\"success\":false,\"message\":\"邮件发送失败\"}");
        }
    }

    private String generateVerificationCode() {
        int min = 100000;
        int max = 999999;
        return String.valueOf((int)(Math.random() * (max - min + 1)) + min);
    }

    private boolean sendVerificationEmail(String toEmail, String code) {
        try {
            Email email = new SimpleEmail();
            email.setHostName("smtp.qq.com"); // SMTP服务器
            email.setSmtpPort(587); // 端口
            email.setAuthenticator(new DefaultAuthenticator("xxxxxxxxxx@xxx.com", "xxxxxxxxxx")); // 替换为你的QQ邮箱和授权码
            email.setStartTLSEnabled(true);

            email.setFrom("xxxxxxxxxx@xxx.com"); // 发件人邮箱
            email.setSubject("邮箱验证码");
            email.setMsg("您的邮箱验证码是：" + code + "，请勿泄露给他人。");
            email.addTo(toEmail); // 收件人邮箱

            email.send();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
